<?php
namespace App\Http\Controllers\Agent;

use App\Http\Controllers\Controller;
use App\Models\Agent\ChaoZongdai;
use App\Models\Log\ChaoMoneyLog;
use App\Models\Role;
use App\Models\Record\ChaoRecord;
use App\Models\User\Tikuan;
use App\Models\User\User;
use App\Models\Agent\TransferLogs;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Models\Lottery\Lottery;

class ChaoZongdaiController extends Controller
{
    public function index(Request $request)
    {
        $admin = Auth::user();

        if ($request->ajax()) {

            $this->validate($request, [
                "begin_time" => "date",
                "end_time"   => "date"
            ]);

            $begin_time = $request->get("begin_time");
            if ($begin_time) {
                $begin_time = date("Y-m-d", strtotime($begin_time));
            }

            $end_time = $request->get("end_time");
            if ($end_time) {
                $end_time = date("Y-m-d", strtotime($end_time)) . " 23:59:59";
            }

            $ChaoZongdai = new ChaoZongdai();

            if ($this->isChaoZongdai()) {
                $admin = Auth::user();
                $ChaoZongdai= ChaoZongdai::where("email", $admin->email);
            }

            $ChaoZongdai = $this->filters($request, $ChaoZongdai);

            $paginator = $ChaoZongdai->orderBy(DB::raw($request->get("sidx")), $request->get("sord"))->paginate($request->get("rows"));
            $rows = [];
            foreach ($paginator as $p) {
                $rows[] = $p;
            }

            if ($rows) {
                $ids = [];
                foreach ($rows as $p) {
                    $ids[] = $p->id;
                }

                $data1 = ChaoZongdai::leftJoin("users", function($join) use ($ids) {
                    $join->on("chao_zongdais.id", "=", "users.chao_zongdai")
                        ->whereIn("chao_zongdais.id", $ids);})
                ->whereRaw("users.zongdai = users.id")
                ->select(DB::raw("
                chao_zongdais.id,
                count(users.id) AS c"))
                ->groupBy("chao_zongdais.id")
                ->get();

                $data2 = ChaoZongdai::leftJoin("users", function($join) use ($ids) {
                    $join->on("chao_zongdais.id", "=", "users.chao_zongdai")
                        ->whereIn("chao_zongdais.id", $ids);})
                    ->whereRaw("users.zongdai <> users.id")
                ->select(DB::raw("
                chao_zongdais.id,
                count(users.id) AS c"))
                ->groupBy("chao_zongdais.id")
                ->get();
                $translog = new TransferLogs();
                foreach ($rows as $p) {
                    $p->money = round($p->money/100, 2);
                    $p->money2 = round(($p->money2 - $translog::where('is_set',0)->where('chao_id',$p->id)->sum('trans_money'))/100, 2);
                    $p->c1 = 0;
                    foreach ($data1 as $p2) {
                        if ($p->id == $p2->id) {
                            $p->c1 = $p2->c;
                        }
                    }
                    $p->c2 = 0;
                    foreach ($data2 as $p2) {
                        if ($p->id == $p2->id) {
                            $p->c2 = $p2->c;
                        }
                    }
                }
            }

            $data = [
                'rows' => $rows,
                'total'=> $paginator->lastPage(),
                'page' => $paginator->currentPage(),
                'records' => $paginator->count(),
            ];

            return response()->json($data);

        } else {

            $c1 = ChaoZongdai::leftJoin("users", function($join) {
                $join->on("chao_zongdais.id", "=", "users.chao_zongdai");})
                ->whereRaw("users.zongdai = users.id")
                ->select(DB::raw("COUNT(1) AS c"));

            $chaoz_id = 0;
            if ($this->isChaoZongdai()) {
                $chaoz_id = ChaoZongdai::where("email", $admin->email)->first()->id;
                $c1 = $c1->where("chao_zongdai", $chaoz_id);
            }
            $c1 = $c1->first()->c;

            $c2 = ChaoZongdai::leftJoin("users", function($join) {
                    $join->on("chao_zongdais.id", "=", "users.chao_zongdai");})
                    ->whereRaw("users.zongdai <> users.id")
                ->select(DB::raw("COUNT(1) AS c"));

            if ($this->isChaoZongdai()) {
                $c2 = $c2->where("chao_zongdai", $chaoz_id);
            }
            $c2 = $c2->first()->c;

            $admin = Auth::user();
            $chaoz = ChaoZongdai::where("email", $admin->email)->first();
            if ($chaoz) {
                $money = round($chaoz->money/100, 2);
            }else{
                $money = 0;
            }

            return view("agent/chao/index", [
                "c1"      => $c1,
                "c2"      => $c2,
                "chaoz"   => $chaoz,
                "money"  =>$money
            ]);
        }
    }

    public function detail(Request $request)
    {
        $this->validate($request, [
            "begin_time" => "date",
            "end_time"   => "date",
        ]);

        $begin_time = $request->get("begin_time");
        if ($begin_time) {
            $begin_time = date("Y-m-d", strtotime($begin_time));
        }

        $end_time = $request->get("end_time");
        if ($end_time) {
            $end_time = date("Y-m-d", strtotime($end_time)) . " 23:59:59";
        }

        if ($request->ajax()) {

            $record = ChaoMoneyLog::join("chao_zongdais", "chao_money_logs.chao_zongdai", "=", "chao_zongdais.id")
            ->select(DB::raw("
                `chao_zongdai`,
                `name`,
                truncate(chao_money_logs.`money`/100, 2) AS `money`,
                truncate(`before`/100, 2) AS `before`,
                truncate(`after`/100, 2) AS `after`,
                `detail`,
                chao_money_logs.create_time AS `chao_money_logs.create_time`"));

            if ($begin_time) {
                $record = $record->where("create_time", ">=", $begin_time);
            }
            
            if ($end_time) {
                $record = $record->where("create_time", ">=", $end_time);
            }

            if ($this->isChaoZongdai()) {
                $admin = Auth::user();
                $chaoz = ChaoZongdai::where("email", $admin->email)->first();
                $record = $record->where("chao_zongdai", $chaoz->id);
            }

            if ($request->get("chao")) {
                $record = $record->where("chao_zongdai", $request->get("chao"));
            }

            $record = $this->filters($request, $record);
            
            $record= $record->orderBy(DB::raw($request->get("sidx")), $request->get("sord"));
            
            $paginator = $record->paginate($request->get("rows"));
            
            $rows = [];
            foreach ($paginator as $p) {
                
                $rows[] = $p;
            }
            
            $data = [
                'rows' => $rows,
                'total'=> $paginator->lastPage(),
                'page' => $paginator->currentPage(),
                'records' => $paginator->count(),
            ];
            return response()->json($data);
            
        } else {
            
            return view("agent/chao/detail");
        }
    }

    public function addMoney(Request $request)
    {
        $this->validate($request, [
            "id"    => "required|integer",
            "money" => "required|integer|min:1|max:99999999"
        ]);

        if ($this->isChaoZongdai()) {
            return response()->json(["success" => false , "message" => "没有权限"]);
        }

        $id = $request->get("id");
        $money = (int)$request->get("money");

        $chao = ChaoZongdai::find($id);

        $old = $chao->money;
        $chao->money += $money * 100;
        $chao->save();

        $chaoMoneyLog = new ChaoMoneyLog();
        $chaoMoneyLog->chao_zongdai = $id;
        $chaoMoneyLog->before = $old;
        $chaoMoneyLog->after  = $chao->money;
        $chaoMoneyLog->money  = $chaoMoneyLog->after - $chaoMoneyLog->before;
        $chaoMoneyLog->detail = Auth::user()->name . " 后台增加";
        $chaoMoneyLog->create_time = date("Y-m-d H:i:s");
        $chaoMoneyLog->save();

        return response()->json(["success" => true]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * id = 1 存 id = 2 取
     * 余额转入保险箱或取出
     */
    public function addMoney2(Request $request)
    {
        $this->validate($request, [
            "id"    => "required|integer",
            "money" => "required|integer|min:1|max:99999999"
        ]);

        $id = $request->get("id");
        $money = ($id==1) ? (int)$request->get("money") : -1*(int)$request->get("money");
        $money *= 100;

        if (!$this->isChaoZongdai()) {
            return response()->json(["success" => false , "message" => "没有权限"]);
        } else {
            $admin = Auth::user();
            $chao= ChaoZongdai::where("email", $admin->email)->first();
        }

        $rel = new TransferLogs();
        $old = $chao->money;
        $old2 = $chao->money2 - $rel::where('is_set',0)->where('chao_id',$chao->id)->sum('trans_money');

        if($id == 1 && $old2 < $money) {
            return response()->json(["success" => false , "message" => "保险箱余额不够"]);
        }
        if($id == 2 && $old < 100*(int)$request->get("money")) {
            return response()->json(["success" => false , "message" => "余额不够"]);
        }

//        if(date('i') > 50) {
//            return response()->json(["success" => false , "message" => "现在不能设置，请稍后重试"]);
//        }
//        try{

        $minute = 2;
        $date = date("YmdHis");
        $date2 = date("Y-m-d H:i:s", time() + $minute * 60);
        $money2 = -$money;
        DB::statement("CREATE EVENT money_to_money2_{$chao->id}_{$date} ON SCHEDULE AT '{$date2}' ON COMPLETION NOT PRESERVE DO CALL money_to_money2({$chao->id}, {$money2})");

//            $rel->zongdai_id = 0;
//            $rel->chao_id = $chao->id;
//            $rel->trans_money = $money*100;
//            $rel->before = $old2;
//            $rel->after = $rel->before - $money*100;
//            $rel->create_time = date("Y-m-d H:i:s");
//            $rel->desc = '';
//            $rel->is_set = 0;
//            $rel->save();
//        } catch( \Exception $e) {
//            return response()->json(["success" => false , "message" => "数据库异常:" . $e->getMessage()]);
//        }
        $message = ($id == 1) ? "保险箱转入余额" : "余额转入保险箱";
        return response()->json(["success" => true,"message" => $message."成功,{$minute}分钟后生效"]);
    }

    public function tikuan(Request $request)
    {
        $admin = Auth::user();

        $memcache = new \Memcached;
        $memcache->addServer('127.0.0.1', 11211);
        $res = $memcache->add("chaoz_tikuan_" . $admin->user_id, "lock", 3);
        if ($res == false) {
            return redirect()->back()->with("message", "请勿重复操作");
        }
        $rmb = $request->get("rmb");

        if (!$this->isChaoZongdai()) {
            return redirect()->back()->with("message", "非法请求");
        } elseif ($rmb <= 0) {
            return redirect()->back()->with("message", "取款金额错误");
            
        } elseif ($rmb != intval($rmb)) {
            return redirect()->back()->with("message", "请输入整数");
            
        } elseif (intval($rmb) % 100 != 0) {
            return redirect()->back()->with("message", "请输入100的整数倍");

        } else {

            DB::beginTransaction();

            $chaozongdai = ChaoZongdai::where("email", $admin->email)->first();
            $old = $chaozongdai->money;

            $rmb = intval($rmb);
            if ($rmb * 100 > $old) {
                return redirect()->back()->with("message", "余额不足");
            }

//             $chaoz->money -= $rmb * 100;
            $affected = DB::update(DB::raw("UPDATE chao_zongdais SET money = money - ? WHERE money >= ? and id = ?"), [$rmb * 100, $rmb * 100, $chaozongdai->id]);
            if (!$affected) {
                return redirect()->back()->with("message", "余额不足");
            }
            $chaoz= ChaoZongdai::find($chaozongdai->id);
            $tikuan = new Tikuan();
            $tikuan->user_id     = $chaoz->id;
            $tikuan->nickname    = $chaoz->name;
            $tikuan->rmb         = $rmb;
            $tikuan->status      = 0;
            $tikuan->user_type   = 1;
            $tikuan->desc        = '';
            $tikuan->id_number   = '';
            $tikuan->card_number = $chaoz->bankcard;
            $tikuan->user_name   = $chaoz->name;
            $tikuan->province    = '';
            $tikuan->city        = '';
            $tikuan->bank_name   = '';
            $tikuan->bank_detail = '';
            $tikuan->create_time = date("Y-m-d H:i:s");
            $tikuan->save();

            $chaoMoneyLog = new ChaoMoneyLog();
            $chaoMoneyLog->chao_zongdai = $chaoz->id;
            $chaoMoneyLog->before = $chaoz->money + $rmb * 100;
            $chaoMoneyLog->after  = $chaoz->money;
            $chaoMoneyLog->money  = -$rmb * 100;
            $chaoMoneyLog->detail = "申请提款";
            $chaoMoneyLog->create_time = date("Y-m-d H:i:s");
            $chaoMoneyLog->save();

            DB::commit();
            $memcache->delete("chaoz_tikuan_" . $admin->user_id);
            return redirect()->back()->with("message", "申请成功");
        }
    }

    public function edit(Request $request)
    {
        $oper = $request->get('oper');

        if ($oper == "add") {

            $this->validate($request, [
                "id"    => "required",
                "email" => "required",
                "ratio" => "int|min:0|max:100"
            ]);

            $email = $request->get('email');
            if (strlen($email) < 6) {
                return response()->json(["success" => false , "message" => "账号要求6位以上"]);
            }

            if (\App\Models\User::where("email", $email)->first()) {
                return response()->json(["success" => false , "message" => "账号已存在"]);
            }

            $role = Role::where("name", "合伙人")->first();
            if (!$role) {
                return response()->json(["success" => false , "message" => "合伙人角色未配置"]);
            }

            $chaoZongdai = new ChaoZongdai();
            $chaoZongdai->email = $email;
            $chaoZongdai->name      = $request->get("name");
            $chaoZongdai->weixin    = $request->get("weixin");
            $chaoZongdai->phone     = $request->get("phone");
            $chaoZongdai->bankcard  = $request->get("bankcard");
            $chaoZongdai->bank_name = $request->get("bank_name");
            $chaoZongdai->desc      = $request->get("desc");
            $chaoZongdai->ratio     = $request->get("ratio");
            $chaoZongdai->create_time = date("Y-m-d H:i:s");
//            $chaoZongdai->gms_id = Auth::user()->user_id;
            $chaoZongdai->save();

            $chaoz = new \App\Models\User();
            $chaoz->name        = $request->get('name');
            $chaoz->email       = $email;
            $chaoz->role_id     = $role->role_id;
            $chaoz->desc        = "合伙人";
//            $chaoz->game_acc_id = 0;
            $chaoz->password    = bcrypt('123456');
            $chaoz->save();

        } else if ($oper == "edit") {

            $this->validate($request, [
                "id"    => "required|integer",
                "ratio" => "int|min:0|max:100"
            ]);

            $id = $request->get("id");

            $chaoZongdai = ChaoZongdai::find($id);
            if (!$chaoZongdai) {
                return redirect()->back()->withErrors("选择的合伙人不存在");
            }

            $ratio = $request->get("ratio");
            $zongdais = User::select(DB::raw("id, zong_ratio"))->whereRaw("users.id = users.zongdai")->where("chao_zongdai",$id)->get();

            if (!empty($zongdais)){
                $max_zong_ratio = 0;
                foreach ($zongdais as $zongdai){
                    if ($zongdai->zong_ratio > $max_zong_ratio){
                        $max_zong_ratio = $zongdai->zong_ratio;
                    }
                }

                if ($ratio < $max_zong_ratio){
                    return response()->json(["success" => false , "message" => "合伙人总比例不能小于下属伙伴的比例"]);
                }
            }

            $chaoZongdai->name      = $request->get("name");
            $chaoZongdai->weixin    = $request->get("weixin");
            $chaoZongdai->phone     = $request->get("phone");
            $chaoZongdai->bankcard  = $request->get("bankcard");
            $chaoZongdai->bank_name = $request->get("bank_name");
            $chaoZongdai->ratio     = $ratio;
            $chaoZongdai->desc      = $request->get("desc");
            $chaoZongdai->save();
        } else if ($oper == "del") {

            $id = $request->get("id");

            $chaoZongdai = ChaoZongdai::find($id);

            if ($chaoZongdai) {

                $count = User::where("chao_zongdai", $chaoZongdai->id)->count();
                if ($count > 0) {
                    return redirect()->back()->withErrors("已有下属总代不能删除");
                }

                $role_id = Role::where("name", "合伙人")->first()->role_id;
                $admin = \App\Models\User::where("email", $chaoZongdai->email)->where("role_id", $role_id)->first();
                $admin->delete();
                $chaoZongdai->delete();
            }
        }

        return response()->json(["success" => true]);
    }
//
//    public function ratio(Request $request)
//    {
//        $this->validate($request, [
//            "id" => "required|integer",
//            "ratio" => "required|integer|min:1|max:100"
//        ]);
//
//        $chao = ChaoZongdai::find($request->get("id"));
//
//        if (!$chao){
//            return redirect()->back()->withErrors("参数错误");
//        }
//
//        $chao->ratio = $request->get("ratio");
//        $chao->save();
//
//        return redirect()->back()->withInput(["message" => "重置密码成功"]);
//    }

    public function tikuanLog(Request $request)
    {
        $this->validate($request, [
            "begin_time" => "date",
            "end_time"   => "date"
        ]);
        
        $begin_time = $request->get("begin_time");
        if ($begin_time) {
            $begin_time = date("Y-m-d", strtotime($begin_time));
        }

        $end_time = $request->get("end_time");
        if ($end_time) {
            $end_time = date("Y-m-d", strtotime($end_time)) . " 23:59:59";
        }

        if ($request->ajax()) {
            $Tikuan = Tikuan::where("user_type", 1);

            if ($begin_time) {
                $Tikuan = $Tikuan->where("create_time", ">=", $begin_time);
            }
            if ($end_time) {
                $Tikuan = $Tikuan->where("create_time", "<=", $end_time);
            }

            $Tikuan = $this->filters($request, $Tikuan);

            $paginator = $Tikuan->orderBy($request->get("sidx"), $request->get("sord"))->paginate($request->get("rows"));

            $rows = [];
            foreach ($paginator as $p) {
                $p->rmb = $p->rmb * 100 / 100;
                $rows[] = $p;
            }

            if ($rows) {
                $ids = [];
                foreach ($rows as $p) {
                    $ids[] = $p->user_id;
                }
                $chaoZongdais = ChaoZongdai::whereIn("id", $ids)->get();
                foreach ($rows as $p) {
                    foreach ($chaoZongdais as $p2) {
                        if ($p->user_id == $p2->id) {
                            $p->email = $p2->email;
                        }
                    }
                }
            }

            $data = [
                'rows' => $rows,
                'total'=> $paginator->lastPage(),
                'page' => $paginator->currentPage(),
                'records' => $paginator->count(),
            ];
            
            return response()->json($data);
        } else {

            return view("agent/tikuan/chao", []);
        }
    }
    
//    public function tikuanExcel(Request $request)
//    {
//        $this->validate($request, [
//            "begin_time" => "date",
//            "end_time"   => "date"
//        ]);
//
//        $begin_time = $request->get("begin_time");
//        if ($begin_time) {
//            $begin_time = date("Y-m-d", strtotime($begin_time));
//        }
//
//        $end_time = $request->get("end_time");
//        if ($end_time) {
//            $end_time = date("Y-m-d", strtotime($end_time)) . " 23:59:59";
//        }
//
//        $fee = 5;
//
//        $AgentRmb = AgentRmb::leftJoin("chao_zongdais", "chao_zongdais.id", "=", "agent_rmbs.user_id")
//        ->select(DB::raw("
//            agent_rmbs.id,
//            time,
//            user_id,
//            user_type,
//            name,
//            email,
//            bankcard,
//            rmb,
//            status"))
//            ->where("user_type", 1);
//
//            if ($begin_time) {
//                $AgentRmb = $AgentRmb->where("agent_rmbs.time", ">=", $begin_time);
//            }
//            if ($end_time) {
//                $AgentRmb = $AgentRmb->where("agent_rmbs.time", "<=", $end_time);
//            }
//
//        $AgentRmb = $this->filters($request, $AgentRmb);
//
//
//        $paginator = $AgentRmb->orderBy("id", "DESC")->get();
//        $fee = 5;
//        $data = [];
//        foreach ($paginator as $p) {
//            $p->rmb -= $fee;
//            $p->time = substr($p->time, 0, 19);
//            $data[] = $p;
//        }
//
//        $cellData = [
//            ["id", "时间", "合伙人ID", "昵称", "账号","银行卡号", "提现金额", "状态"]
//        ];
//
//        foreach($data as $key => $value) {
//
//            $status = '';
//            if ($value->status == 0) {
//                $status = "审核中";
//            } elseif ($value->status == 2) {
//                $status = "通过";
//            } elseif ($value->status == 3) {
//                $status = "拒绝";
//            }
//
//            $cellData[] = [$value->id , $value->time , $value->user_id , $value->name, $value->email, $value->bankcard, $value->rmb ,  $status];
//        }
//
//        Excel::create(date("YmdHis"), function($excel) use ($cellData){
//            $excel->sheet('score', function($sheet) use ($cellData){
//                $sheet->rows($cellData);
//            });
//        })->export('xlsx');
//    }

    public function record(Request $request)
    {
        if ($request->ajax()){

            $record = ChaoRecord::join("shishicai", "number", "=", "issue")->select(DB::raw("
                number,
                chao_zongdai,
                nickname,
                chao_records.kjcode,
                ratio,
                truncate(chao_records.win/100,2) as win,
                truncate(chao_records.money/100,2) as money,
                truncate(chao_records.spend/100,2) as spend,
                create_time"));

            $record= $this->filters($request, $record);

            if ($this->isChaoZongdai()) {
                $admin = Auth::user();
                $ChaoZongdai= ChaoZongdai::where("email", $admin->email)->first();
                $record = $record->where("chao_zongdai", $ChaoZongdai->id);
            }
            $paginator = $record->orderBy($request->get("sidx"), $request->get("sord"))->paginate($request->get("rows"));

            $rows = [];
            $numbers = [];
            foreach ($paginator as $page){
                $rows[] = $page;
                $numbers[] = $page->number;
            }

            $lotterys = Lottery::select(DB::raw("issue, kjcodes"))->whereIn("issue", $numbers)->get();

            if ($rows){
                foreach ($rows as $row){
                    foreach ($lotterys as $lottery){
                        if ($row->number == $lottery->issue){
                            $row->kjcodes = $lottery->kjcodes;
                        }
                    }
                }
            }
            
            $data = [
                'rows' => $rows,
                'total'=> $paginator->lastPage(),
                'page' => $paginator->currentPage(),
                'records' => $paginator->count(),
            ];
            
            return response()->json($data);
            
        } else {
            return view('agent/chao/record');
        }
        
    }
    
    public function resetpwd(Request $request)
    {
        $this->validate($request, [
            "id" => "required|integer"
        ]);

        $id = (int)$request->get("id");

        $email = ChaoZongdai::find($id)->email;

        $chaoz = \App\Models\User::where("email", $email)->first();

        $role_id = Role::where("name", "合伙人")->first()->role_id;
        if ($chaoz && $chaoz->role_id == $role_id) {
            $chaoz->password = bcrypt("123456");
            $chaoz->save();
        }else{
            return redirect()->back()->withErrors("参数错误");
        }

        return response()->json(["success" => true]);
    }
}
